package com.nervenets.web.config;

import com.nervenets.Global;
import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.PropertiesLoader;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.dao.*;
import com.nervenets.web.hibernate.domain.Manager;
import com.nervenets.web.redis.GlobalService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.annotation.Resource;

/**
 * Created by Joe on 2018/1/8.
 */
@Configuration
public class ApplicationConfiguration implements InitializingBean {
    @Resource
    private ManagerDao managerDao;
    @Resource
    private GlobalService globalService;
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("检查系统初始化数据...");
        final PropertiesLoader propertiesLoader = Global.getApplicationProperties();
        String defaultUsername = propertiesLoader.getProperty("app.admin.account");
        String defaultPassword = propertiesLoader.getProperty("app.admin.password");
        System.out.println("查询并设置系统默认管理账号:" + defaultUsername + ",密码:" + defaultPassword);

        Manager manager = managerDao.findManagerByMobile(defaultUsername);

        if (null == manager) {
            System.out.println("开始初始化系统基本参数...");
            manager = new Manager(defaultUsername, defaultPassword);
            manager.setName("超级管理员");
            manager.setRole(Role.admin);
            managerDao.save(manager);

            globalService.clearRedis();

            System.out.println("结束初始化系统基本参数...");
        }
        baseStatisticsDomainGenerate();
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedHeaders("*")
                        .allowedMethods("*")
                        .allowedOrigins("*")
                        .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                        .maxAge(3600)
                        .allowCredentials(true);
            }
        };
    }

    private void baseStatisticsDomainGenerate() {
        System.out.println("检查统计基础数据是否生成...");
        final int mtStart = JodaUtils.getEndOfToday() + 1;

        System.out.println("检查统计基础数据是否生成完成");
    }
}
